/* mock TTS Server to play an audio file dispite what text received */

const fs = require('fs');
const ws = require('ws');
const http = require('http');
const express = require('express')
const app = express()
const port = 9000

//initialize a simple http server
const server = http.createServer(app);
//initialize the WebSocket server instance
const wss = new ws.Server({ server });
const audioFile = "vacation.wav"

let packets = 0;
let bytes = 0;

wss.on('connection', (s) => {
	console.log("ws client connected");
	s.on('message', (message, isBinary) => {
		console.log('received: isBinary=%s type=%s length=%d packets=%d', isBinary, typeof(message), message.length, packets);

		if (isBinary) { // Audio Data
				console.log("TTS is not supposed to send binary to me, ignoring ...");
		} else {
			const rpc = JSON.parse(message)
			console.log(rpc);
	
			if (rpc.method == "start") {
				handle_start(s, rpc);
			}
		}
	});
});

function handle_start(s, rpc) {
	const defaultParams = {
		ms: 100,
		rate: 8000,
	}
	const params = Object.assign(defaultParams, rpc.params);
	console.log("params", params);

	reply = {
		jsonrpc: "2.0",
		id: rpc.id,
		result: {
			code: 200,
			message: "OK",
			audio: "sendonly",
		}
	}

	console.log("send", reply);
	const str = JSON.stringify(reply);
	s.send(str);

	const chunkSize = params.rate * params.ms / 1000 * 2;
	console.log("chunkSize", chunkSize);

	// read all samples from file
	samples = fs.readFileSync("vacation-" + params.rate + ".pcm");
	packets = bytes = 0;

	const sendChunk = () => {
		const chunk = samples.slice(0, chunkSize);
		samples = samples.slice(chunkSize);

		if (s.readyState != ws.OPEN || chunk.length == 0) {
			console.log("done", packets, "packets", bytes, "bytes");
			s.close();
			return;
		}

		console.log(new Date().toISOString(), "sending data", chunk.length);

		s.send(chunk, {binary: true});
		packets++;
		bytes += chunk.length;
		setTimeout(sendChunk, params.ms / 2); // 2x speed
	}
	sendChunk();
}

wss.on('close', () => {
	console.log("closed");
	packets = 0;
});

server.listen(port, () => {
	console.log(`Example TTS Server listening at http://localhost:${port}`)
})
